<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Area;
use app\common\model\Attachment;
use app\common\model\MoneyLog;
use app\common\model\wash\Order;
use app\common\model\wash\Serviceorder;
use fast\Date;
use think\Db;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{

    protected $noNeedRight = ['ajax'];
    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }

        $group_ids = $this->auth->getGroupIds();
        $group_id = $group_ids[0];
        $type = '';
        if ($group_id == 1) {

        } elseif ($group_id == 2) {
            $type = 'region';
        } elseif ($group_id == 5) {
            $type = 'subsidiary';
        }

        $category_list = \app\common\model\Category::where(['type' => 'notice', 'status' => 'normal'])->order('weigh ASC, id DESC')->select();
        $cateList = [];
        foreach ($category_list as $category) {
            $cateList[$category['id']] = $category['name'];
        }
        $this->view->assign('cateList', $cateList);
        $this->assignconfig('cateList', $cateList);

        $region_id = $this->request->param('region_id', '');
        $company_id = $this->request->param('company_id', '');

        $admin = $this->auth->getUserInfo();
        $group_ids = $this->auth->getGroupIds();
        $group_id1 = $group_ids[0];
        if ($region_id != '') {
            $admin = Admin::get(intval($region_id));
            $group_ids = (new \app\admin\library\Auth)->getGroupIds($region_id);
            $company_id = -1;
        } elseif ($company_id != '') {
            $admin = Admin::get(intval($company_id));
            $group_ids = (new \app\admin\library\Auth)->getGroupIds($company_id);
            $region_id = $admin['pid'];
        }

        $group_id = $group_ids[0];

        switch ($group_id) {
            case 1:
                # - 超级管理员
                $totalfactory = User::where(['role' => 'factory'])->count();
                $totalfactorycommission = User::where(['role' => 'factory'])->sum('commission');
                $totalshop = User::where(['role' => 'shop'])->count();
                $totalshopcommission = User::where(['role' => 'shop'])->sum('commission');

                $where = [];
                break;
            case 2:
                # - 城市管理员
                $ids = Area::where('pid', $admin['region_id'])->column('id');

                $adminmodel = new \app\common\model\Admin;
                foreach ($ids as $v) {
                    $adminmodel->whereOr("FIND_IN_SET({$v}, region_id)");
                }
                $admin_ids = $adminmodel->column('id');
                $area_count = count($admin_ids);
                array_push($admin_ids, $admin['id']);

                $totalfactory = User::where(['role' => 'factory', 'company_id' => ['IN', $admin_ids]])->count();
                $totalfactorycommission = User::where(['role' => 'factory', 'company_id' => ['IN', $admin_ids]])->sum('commission');
                $totalshop = User::where(['role' => 'shop', 'company_id' => ['IN', $admin_ids]])->count();
                $totalshopcommission = User::where(['role' => 'shop', 'company_id' => ['IN', $admin_ids]])->sum('commission');

                $where = ['regional_id' => $admin['id']];

                $this->view->assign('area_count', $area_count);
                break;
            case 5:
                # - 区县管理员
                AuthGroupAccess::where('group_id', 2)->column('uid');

                $totalfactory = User::where(['role' => 'factory', 'company_id' => $admin['id']])->count();
                $totalfactorycommission = User::where(['role' => 'factory', 'company_id' => $admin['id']])->sum('commission');
                $totalshop = User::where(['role' => 'shop', 'company_id' => $admin['id']])->count();
                $totalshopcommission = User::where(['role' => 'shop', 'company_id' => $admin['id']])->sum('commission');

                $where = ['regional_id' => $admin['pid'], 'company_id' => $admin['id']];
                break;
            default:
                break;
        }

        # - 清洗订单 + 家政订单 + 商城订单 + 充值订单 统计
        $wash_order_money = Order::where($where)->where('status', '>', '0')->sum('total_fee');
        $service_order_money = Serviceorder::where($where)->where('status', '>', '0')->sum('total_fee');
        $shop_order_money = \app\common\model\Order::where($where)->where('status', '>', '0')->sum('total_money');

        $wash_order_count = Order::where($where)->where('status', '>', '0')->count();
        $service_order_count = Serviceorder::where($where)->where('status', '>', '0')->count();
        $shop_order_count = \app\common\model\Order::where($where)->where('status', '>', '0')->count();

        $today_wash_order_money = Order::where($where)->where('status', '>', '0')->whereTime('paytime', 'today')->sum('total_fee');
        $today_service_order_money = Serviceorder::where($where)->where('status', '>', '0')->whereTime('paytime', 'today')->sum('total_fee');
        $today_shop_order_money = \app\common\model\Order::where($where)->where('status', '>', '0')->whereTime('paytime', 'today')->sum('total_money');

        $today_wash_order_count = Order::where($where)->whereTime('paytime', 'today')->count();
        $today_service_order_count = Serviceorder::where($where)->whereTime('paytime', 'today')->count();
        $today_shop_order_count = \app\common\model\Order::where($where)->whereTime('paytime', 'today')->count();

        $totalvoucher = \app\common\model\voucher\Order::where($where)->where('is_pay', 1)->sum('money');
        $todayvoucher = \app\common\model\voucher\Order::where($where)->where('is_pay', 1)->whereTime('pay_time', 'today')->sum('money');


        # - 余额支付订单数量统计
        $where['pay_type'] = 'money';
        $wash_order_money_count = Order::where($where)->where('status', '>', '0')->count();
        $service_order_money_count = Serviceorder::where($where)->where('status', '>', '0')->count();

        $this->view->assign([
            'region_id'             => $region_id,
            'company_id'            => $company_id,
            'group_id'              => $group_id,
            'group_id1'             => $group_id1,
            'totaluser'             => User::where(['role' => 'user'])->count(),
            'todayuser'             => User::whereTime('jointime', 'today')->where(['role' => 'user'])->count(),
            'totalorder'            => $wash_order_count + $service_order_count + $shop_order_count,
            'totalmoney'            => $wash_order_money + $service_order_money + $shop_order_money,
            'todaymoney'            => $today_wash_order_money + $today_service_order_money + $today_shop_order_money,
            'todayorder'            => $today_wash_order_count + $today_service_order_count + $today_shop_order_count,
            'totalvoucher'          => $totalvoucher,
            'todayvoucher'          => $todayvoucher,
            'city_count'            => AuthGroupAccess::where('group_id', 2)->count(),
            'totalfactory'          => $totalfactory,
            'totalshop'             => $totalshop,
            'totalfactorycommission'=> $totalfactorycommission,
            'totalshopcommission'   => $totalshopcommission,
            'totalmoneyorder'       => $wash_order_money_count + $service_order_money_count
        ]);


//        $admins = Admin::where('id', 'in', $adminids)->select();
//        foreach ($admins as $admin) {
//            $admin->total_money = MoneyLog::where('admin_id', $admin->id)->where('money', '>', 0)->sum('money');
//            $admin->wash_order_money = Order::where('regional_id', $admin->id)->where('status', '>', '0')->sum('total_fee');
//            $admin->service_order_money = Serviceorder::where('regional_id', $admin->id)->where('status', '>', '0')->sum('total_fee');
//            $admin->today_wash_order_money = Order::where('regional_id', $admin->id)->where('status', '>', '0')->whereTime('paytime', 'd')->sum('total_fee');
//            $admin->today_service_order_money = Serviceorder::where('regional_id', $admin->id)->where('status', '>', '0')->whereTime('paytime', 'd')->sum('total_fee');
//            $admin->today_totalmoney = $admin->today_wash_order_money + $admin->today_service_order_money;
//            $admin->totalmoney = $admin->wash_order_money + $admin->service_order_money;
//            $admin->totalmoney = $admin->wash_order_money + $admin->service_order_money;
//            $admin->wash_order_count = Order::where('regional_id', $admin->id)->where('status', '>', '0')->count();
//            $admin->service_order_count = Serviceorder::where('regional_id', $admin->id)->where('status', '>', '0')->count();
//            $admin->today_wash_order_count = Order::where('regional_id', $admin->id)->whereTime('paytime', 'd')->where('status', '>', '0')->count();
//            $admin->today_service_order_count = Serviceorder::where('regional_id', $admin->id)->whereTime('paytime', 'd')->where('status', '>', '0')->count();
//            $admin->today_totalorder = $admin->today_wash_order_count + $admin->today_service_order_count;
//            $admin->totalorder = $admin->wash_order_count + $admin->service_order_count;
//
//            $company_ids = Admin::where('pid', $admin->id)->column('id');
//            $admin->company = 0;
//            $admin->shop = 0;
//            $admin->factory = 0;
//
//            if (count($company_ids)) {
//                $admin->company = count($company_ids);
//                $admin->shop = User::where('company_id', 'in', $company_ids)->where('role', 'shop')->count();
//                $admin->factory = User::where('company_id', 'in', $company_ids)->where('role', 'factory')->count();
//            }
//        }
//
//        if ($group_id == 5) {
//            $admin_ids = $this->auth->id;
//        } else {
//            $admin_ids = AuthGroupAccess::where('group_id', 5)->column('uid');
//        }
//        $admin_s = Admin::where('id', 'in', $admin_ids)->select();
//        foreach ($admin_s as $admin) {
//            $admin->total_money = MoneyLog::where('admin_id', $admin->id)->where('money', '>', 0)->sum('money');
//            $admin->wash_order_money = Order::where('company_id', $admin->id)->where('status', '>', '0')->sum('total_fee');
//            $admin->service_order_money = Serviceorder::where('company_id', $admin->id)->where('status', '>', '0')->sum('total_fee');
//            $admin->today_wash_order_money = Order::where('company_id', $admin->id)->where('status', '>', '0')->whereTime('paytime', 'd')->sum('total_fee');
//            $admin->today_service_order_money = Serviceorder::where('company_id', $admin->id)->where('status', '>', '0')->whereTime('paytime', 'd')->sum('total_fee');
//            $admin->today_totalmoney = $admin->today_wash_order_money + $admin->today_service_order_money;
//            $admin->totalmoney = $admin->wash_order_money + $admin->service_order_money;
//            $admin->wash_order_count = Order::where('company_id', $admin->id)->where('status', '>', '0')->count();
//            $admin->service_order_count = Serviceorder::where('company_id', $admin->id)->where('status', '>', '0')->count();
//            $admin->totalorder = $admin->wash_order_count + $admin->service_order_count;
//            $admin->today_wash_order_count = Order::where('company_id', $admin->id)->whereTime('paytime', 'd')->where('status', '>', '0')->count();
//            $admin->today_service_order_count = Serviceorder::where('company_id', $admin->id)->whereTime('paytime', 'd')->where('status', '>', '0')->count();
//            $admin->today_totalorder = $admin->today_wash_order_count + $admin->today_service_order_count;
//
//            $admin->shop = User::where('company_id', $admin->id)->where('role', 'shop')->count();
//            $admin->factory = User::where('company_id', $admin->id)->where('role', 'factory')->count();
//        }


        return $this->view->fetch();
    }

    public function ajax()
    {
        $region_id = $this->request->param('region_id', '');
        $company_id = $this->request->param('company_id', '');

        $admin = $this->auth->getUserInfo();
        $group_ids = $this->auth->getGroupIds();
        if ($region_id != '') {
            $admin = Admin::get(intval($region_id));
            $group_ids = (new \app\admin\library\Auth)->getGroupIds($region_id);
        } elseif ($company_id != '') {
            $admin = Admin::get(intval($company_id));
            $group_ids = (new \app\admin\library\Auth)->getGroupIds($company_id);
        }

        $group_id = $group_ids[0];

        switch ($group_id) {
            case 2:
                $where['regional_id'] = $admin['id'];
                break;
            case 5:
                $where['company_id'] = $admin['id'];
                break;
            default:
                $where = [];
                break;
        }

        $time = $this->request->request('time', '');

        $time_data = $time == '' ? $this->getDateArray('month') : $this->getDateArray($time);
        $y = []; $x = $time_data ? $time_data['x'] : '';

        $type = $this->request->request('type');

        switch ($type) {
            case 'pie_echart1':
                $title = '';
                $legend = ['orient' => 'horizontal', 'bottom' => 20];

                $data = [
                    [
                        'value' => Order::where($where)->count(),
                        'name' => '清洗订单'
                    ],
                    [
                        'value' => Serviceorder::where($where)->count(),
                        'name' => '家政订单'
                    ],
                    [
                        'value' => \app\common\model\Order::where($where)->count(),
                        'name' => '商城订单'
                    ]
                ];

                $series = [
                    [
                        'type'      => 'pie',
                        'radius'    => '50%',
                        'data'      => $data,
                        'emphasis'  => [
                            'itemStyle' => [
                                'shadowBlur'    => 10,
                                'shadowOffsetX' => 0,
                                'shadowColor'   => 'rgba(0, 0, 0, 0.5)'
                            ]
                        ]
                    ]
                ];
                break;
            case 'pie_echart2':
                $title = '';
                $legend = ['orient' => 'horizontal', 'bottom' => 20];

                $data = [
                    [
                        'value' => Order::where($where)->where('status', '>', 0)->sum('total_fee'),
                        'name' => '清洗订单'
                    ],
                    [
                        'value' => Serviceorder::where($where)->where('status', '>', 0)->sum('total_fee'),
                        'name' => '家政订单'
                    ],
                    [
                        'value' => \app\common\model\Order::where($where)->where('status', '>', 0)->sum('total_money'),
                        'name' => '商城订单'
                    ]
                ];

                $series = [
                    [
                        'type'      => 'pie',
                        'radius'    => '50%',
                        'data'      => $data,
                        'emphasis'  => [
                            'itemStyle' => [
                                'shadowBlur'    => 10,
                                'shadowOffsetX' => 0,
                                'shadowColor'   => 'rgba(0, 0, 0, 0.5)'
                            ]
                        ]
                    ]
                ];
                break;
            case 'item_echart':
                $title = '趋势图';
                $legend = ['销售额', '充值额'];


                # - 销售额 清洗订单+家政订单+商城订单
                $wash_order_list = Order::where('paytime', 'between time', [$time_data['starttime'], $time_data['endtime']])
                    ->where($where)
                    ->where('status', '>', '0')
                    ->field('sum(total_fee) AS total_fee, DATE_FORMAT(FROM_UNIXTIME(paytime), "' . $time_data['from_unixtime'] . '") AS date')
                    ->group('date')
                    ->select();

                $service_order_list = Serviceorder::where('paytime', 'between time', [$time_data['starttime'], $time_data['endtime']])
                    ->where($where)
                    ->where('status', '>', '0')
                    ->field('sum(total_fee) AS total_fee, DATE_FORMAT(FROM_UNIXTIME(paytime), "' . $time_data['from_unixtime'] . '") AS date')
                    ->group('date')
                    ->select();

                $goods_order_list = \app\common\model\Order::where('paytime', 'between time', [$time_data['starttime'], $time_data['endtime']])
                    ->where($where)
                    ->where('status', '>', '0')
                    ->field('sum(total_money) AS total_fee, DATE_FORMAT(FROM_UNIXTIME(paytime), "' . $time_data['from_unixtime'] . '") AS date')
                    ->group('date')
                    ->select();

                # - 充值额
                $voucher_order_list = \app\common\model\voucher\Order::where('pay_time', 'between time', [$time_data['starttime'], $time_data['endtime']])
                    ->where($where)
                    ->where(['is_pay' => 1])
                    ->field('sum(money) AS total_money, DATE_FORMAT(FROM_UNIXTIME(pay_time), "' . $time_data['from_unixtime'] . '") AS date')
                    ->group('date')
                    ->select();

                $order_list = $voucher_list = [];
                foreach ($time_data['x'] as $key => $val) {
                    $i = $j = 0;
                    foreach ($wash_order_list as $k => $v) {
                        if ($val == $v['date']) {
                            $i += $v['total_fee']; unset($wash_order_list[$k]);
                            break;
                        }
                    }

                    foreach ($service_order_list as $k => $v) {
                        if ($val == $v['date']) {
                            $i += $v['total_fee']; unset($service_order_list[$k]);
                            break;
                        }
                    }

                    foreach ($goods_order_list as $k => $v) {
                        if ($val == $v['date']) {
                            $i += $v['total_fee']; unset($goods_order_list[$k]);
                            break;
                        }
                    }

                    foreach ($voucher_order_list as $k => $v) {
                        if ($val == $v['date']) {
                            $j = $v['total_money']; unset($voucher_order_list[$k]);
                            break;
                        }
                    }

                    $order_list[] = $i;
                    $voucher_list[] = $j;
                }

                $series = [
                    [
                        'name' => '销售额',
                        'type' => 'line',
                        'areaStyle'=> [ 'normal'=> ''],
                        'data' => $order_list
                    ],
                    [
                        'name' => '充值额',
                        'type' => 'line',
                        'areaStyle'=> [ 'normal'=> ''],
                        'data' => $voucher_list
                    ]
                ];
                break;
            case 'item_echart2':
                $title = '充值额趋势图';

                break;
            default:
                break;
        }

        $this->success('success', '', ['title' => $title, 'x' => $x, 'series' => $series, 'legend' => $legend]);
    }

    /**
     * 获取数据 备注日期都不带前导0
     */
    protected function getDateArray($type) {

        $data = $dateArray = array();

        switch($type) {
            case 'year':
//                for($i = 1; $i <= 12; $i++) {
//                    $starttime = strtotime(date('Y-' . $i . '-01'));
//                    $endtime = strtotime("+1 month -1 second", $starttime);
//                    array_push($dateArray, date('Y-') . $i);
//                    array_push($data, ['starttime' => $starttime, 'endtime' => $endtime]);
//                }
//
//                $from_unixtime = "%Y-%c";
//                $starttime = strtotime(date('Y-01-01'));
//                $endtime = strtotime("+12 month -1 second", $starttime);
//                break;

            case 'quarter':
                $value = ceil((date('n'))/3);

                $firstMonth = ($value * 3) - 2;
                for($i = $firstMonth; $i <= $firstMonth + 2; $i++) {
                    $starttime = strtotime(date('Y-' . $i . '-01'));
                    $endtime = strtotime("+1 month -1 second", $starttime);
                    array_push($dateArray, date('Y-') . $i);
                    array_push($data, ['starttime' => $starttime, 'endtime' => $endtime]);
                }

                $from_unixtime = "%Y-%c";
                $starttime = strtotime(date('Y-' . $firstMonth . '-01'));
                $endtime = strtotime("+3 month -1 second", $starttime);
                break;

            case 'month':
                for($i = 1; $i <= date("t", strtotime(date('Y-m'))); $i++) {
                    $starttime = strtotime(date('Y-m-' . $i));
                    $endtime = $starttime + 86399;
                    array_push($dateArray, date('Y-n-' . $i));
                    array_push($data, ['starttime' => $starttime, 'endtime' => $endtime]);
                }

                $from_unixtime = "%Y-%c-%e";
                $starttime = strtotime(date('Y-n'));
                $endtime = strtotime("+1 month -1 second", $starttime);
                break;

            case 'week':
                $startOfWeek = strtotime('monday this week');
                for($i = 0; $i < 7; $i++) {
                    $day = date('Y-n-j', strtotime('+' . $i . ' days', $startOfWeek));
                    $starttime = strtotime($day);
                    $endtime = $starttime + 86399;
                    array_push($dateArray, $day);
                    array_push($data, ['starttime' => $starttime, 'endtime' => $endtime]);
                }
                $from_unixtime = "%Y-%c-%e";
                $starttime = strtotime(date('Y-m-d', $startOfWeek));
                $endtime = $starttime + 86400 * 7 -1;
                break;

            case 'day':
                for($i = 0; $i < 24; $i++) {
                    $starttime = mktime($i, 0, 0, date('m'), date('d'), date('Y'));
                    $endtime = $starttime + 3600;
                    array_push($dateArray, date('Y-n-j ') . $i);
                    array_push($data, ['starttime' => $starttime, 'endtime' => $endtime]);
                }

                $from_unixtime = "%Y-%c-%e %k";
                $starttime = strtotime(date('Y-m-d'));
                $endtime = $starttime + 86399;
                break;

            default:
                # - 自定义时间段
                $time = explode(' - ', $type);
                $starttime = strtotime($time[0]);
                $endtime = strtotime($time[1]);
                $days = ($endtime - $starttime) / 86400 + 1;

                for($i = 1; $i <= $days; $i++) {
                    $start = $starttime + ($i - 1) * 86400;
                    $end = $starttime + 86399;
                    array_push($dateArray, date('Y-n-j', $start));
                    array_push($data, ['starttime' => $start, 'endtime' => $end]);
                }

                $from_unixtime = "%Y-%c-%e";
                break;

                break;
        }

        # - x:横坐标轴坐标;time:x坐标轴对应坐标的时间区间;from_unixtime:y轴数据按某时间格式统计数据;starttime:开始时间;endtime:结束时间
        return [ 'time' => $data, 'x' => $dateArray, 'from_unixtime' => $from_unixtime, 'starttime' => $starttime, 'endtime' => $endtime ];
    }
}
